<!-- eslint-disable vue/no-use-v-if-with-v-for -->
<!-- eslint-disable vue/valid-v-slot -->
<template>
  <div class="main-container">
    <TableBody>
      <template #header>
        <TableHeader ref="tableHeaderRef" :show-filter="false">
          <template #search-content>
            <a-form ref="seachFormRef" :model="seachForm">
              <a-row :gutter="24">
                <a-col :span="4">
                  <a-form-item field="adminId" hide-label>
                    <Inputs :cards="seachForm.cards" @update="cardFn" />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="outTradeNo" hide-label>
                    <a-input v-model="seachForm.outTradeNo" placeholder="请输入订单号" />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="userIds" hide-label>
                    <a-select
                      v-model="seachForm.userIds"
                      multiple
                      :max-tag-count="1"
                      allow-clear
                      allow-search
                      placeholder="请选择客户"
                      :options="userList"
                      :virtual-list-props="{ height: 200 }"
                  /></a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="channelIds" hide-label>
                    <a-select
                      v-model="seachForm.channelIds"
                      multiple
                      :max-tag-count="1"
                      allow-clear
                      allow-search
                      placeholder="请选择渠道"
                    >
                      <a-option
                        v-for="(item, index) in channelList"
                        :key="index"
                        :value="item.id"
                        >{{ item.name }}</a-option
                      >
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="seriesIds" hide-label>
                    <a-select
                      v-model="seachForm.seriesIds"
                      :max-tag-count="1"
                      allow-clear
                      allow-search
                      placeholder="请选择系列"
                      multiple
                    >
                      <a-option v-for="(item, index) in serieList" :key="index" :value="item.id">{{
                        item.name
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="setMealIds" hide-label>
                    <a-select
                      v-model="seachForm.setMealIds"
                      :max-tag-count="1"
                      allow-clear
                      placeholder="请选择套餐"
                      multiple
                      allow-search
                    >
                      <a-option v-for="(item, index) in mealList" :key="index" :value="item.id">{{
                        item.name
                      }}</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="states" hide-label>
                    <a-select
                      v-model="seachForm.states"
                      multiple
                      :max-tag-count="1"
                      placeholder="请选择返佣状态"
                      allow-clear
                    >
                      <a-option :value="0">等待返佣</a-option>
                      <a-option :value="1">返佣成功</a-option>
                      <a-option :value="2">返佣收回</a-option>
                      <a-option :value="3">回收失败</a-option>
                      <a-option :value="4">返佣失败</a-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addTime" hide-label>
                    <a-date-picker
                      v-model="seachForm.addTime"
                      style="width: 100%"
                      show-time
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      placeholder="请选择开始时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="endTime" hide-label>
                    <a-date-picker
                      v-model="seachForm.endTime"
                      style="width: 100%"
                      show-time
                      :shortcuts="[
                        {
                          label: '今日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            ))
                          ),
                        },
                        {
                          label: '昨日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs('23:59:59', 'HH:mm:ss')
                              .subtract(1, 'day')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '七日',
                          value: () => (
                            (seachForm.addTime = $dayjs('00:00:00', 'HH:mm:ss')
                              .subtract(6, 'day')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '本月',
                          value: () => (
                            (seachForm.addTime = $dayjs('01 00:00:00', 'DD HH:mm:ss').format(
                              'YYYY-MM-DD HH:mm:ss'
                            )),
                            (seachForm.endTime = $dayjs().format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                        {
                          label: '上月',
                          value: () => (
                            (seachForm.addTime = $dayjs(`01 00:00:00`, 'DD HH:mm:ss')
                              .subtract(1, 'month')
                              .format('YYYY-MM-DD HH:mm:ss')),
                            (seachForm.endTime = $dayjs()
                              .subtract(1, 'month')
                              .endOf('month')
                              .format('YYYY-MM-DD HH:mm:ss'))
                          ),
                        },
                      ]"
                      placeholder="请选择结束时间"
                      :time-picker-props="{ defaultValue: '12:00:00' }"
                      format="YYYY-MM-DD HH:mm:ss"
                      allow-clear
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="addAmount" hide-label>
                    <a-input-group style="width: 100%">
                      <a-input
                        hide-button
                        v-model="seachForm.addAmount"
                        placeholder="开始返佣金额"
                      />
                      <a-input
                        hide-button
                        v-model="seachForm.endAmount"
                        placeholder="结束返佣金额"
                      />
                    </a-input-group>
                  </a-form-item>
                </a-col>
                <a-col :span="4">
                  <a-form-item field="btns" hide-label>
                    <a-space :size="15">
                      <a-button
                        type="primary"
                        v-permission="rebateList"
                        html-type="submit"
                        @click="doRefresh(1)"
                        ><template #icon>
                          <icon-search />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>搜索</template></a-button
                      >
                      <a-button v-permission="rebateList" @click="resetSeach"
                        ><template #icon>
                          <icon-sync theme="outline" size="14" />
                        </template>
                        <!-- Use the default slot to avoid extra spaces -->
                        <template #default>重置</template></a-button
                      >
                    </a-space>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-form>
          </template>
        </TableHeader>
      </template>
      <template #table-config>
        <a-space :size="15">
          <a-button
            type="outline"
            v-permission="rebateListexport"
            :loading="loading"
            @click="exportList"
          >
            <!-- Use the default slot to avoid extra spaces -->
            <template #default>导出</template>
          </a-button>
        </a-space>
        <a-space :size="15">
          <TableConfig
            @update-border="onUpdateBorder"
            @update-striped="onUpdateStriped"
            @refresh="doRefresh"
          />
        </a-space>
      </template>
      <template #default>
        <a-table
          :bordered="{ wrapper: true, cell: tables.bordered }"
          :stripe="(tables.striped as boolean)"
          :loading="tableLoading"
          :data="table.dataList"
          :pagination="false"
          :column-resizable="true"
          :rowKey="rowKey"
          :columns="tableColumns.list"
          :scrollbar="true"
          :scroll="{ x: 1200 }"
          table-layout-fixed
        >
          <template #columns>
            <a-table-column
              v-for="item of tableColumns.list"
              :key="item.key"
              align="left"
              :width="item.width"
              :ellipsis="true"
              :tooltip="true"
              :title="(item.title as string)"
              :data-index="(item.key as string)"
              :fixed="item.fixed"
            >
              <template v-if="item.key === 'userName'" #cell="{ record }">
                {{ record.user.userName }}
              </template>
              <template v-if="item.key === 'card'" #cell="{ record }">
                {{ record.card.card }}
              </template>
              <template v-if="item.key === 'setMealName'" #cell="{ record }">
                {{ record.order.setMealName }}
              </template>
              <template v-if="item.key === 'addTime'" #cell="{ record }">
                {{ record.order.createTime }}
              </template>
              <template v-else-if="item.key === 'state'" #cell="{ record }">
                <a-tag v-if="record.state === 0">等待返佣</a-tag>
                <a-tag color="blue" v-else-if="record.state === 1">返佣成功</a-tag>
                <a-tag color="red" v-else-if="record.state === 2">返佣收回</a-tag>
                <a-tag color="red" v-else-if="record.state === 3">回收失败</a-tag>
                <a-tag color="red" v-else-if="record.state === 4">返佣失败</a-tag>
              </template>
              <template v-else-if="item.key === 'action'" #cell="{ record }">
                <a-button type="text" @click="detailFn(record)">详情</a-button>
                <a-button v-permission="rebaterecovery" type="text" @click="rebateDel(record)"
                  >收回</a-button
                >
              </template>
            </a-table-column>
          </template>
        </a-table>
      </template>
      <template #footer>
        <TableFooter ref="tableFooterRef" :pagination="pagination" />
      </template>
    </TableBody>
    <!-- 详情 -->
    <a-modal v-model:visible="visible" :mask-closable="false" width="800px" title="返佣详情">
      <div>
        <a-descriptions :column="2" align="center" bordered>
          <a-descriptions-item label="客户账号">{{
            detail.user ? detail.user.userName : '管理员'
          }}</a-descriptions-item>
          <a-descriptions-item label="卡号">{{ detail.card.card }}</a-descriptions-item>
          <a-descriptions-item label="套餐名称">{{ detail.order.setMealName }}</a-descriptions-item>
          <a-descriptions-item label="返佣金额">{{ detail.amount }}</a-descriptions-item>
          <a-descriptions-item label="返佣状态">
            <a-tag v-if="detail.state === 0">等待返佣</a-tag>
            <a-tag color="blue" v-else-if="detail.state === 1">返佣成功</a-tag>
            <a-tag color="red" v-else-if="detail.state === 2">返佣回收</a-tag>
            <a-tag color="red" v-else-if="detail.state === 3">回收失败</a-tag>
            <a-tag color="red" v-else-if="detail.state === 4">返佣失败</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="返佣单号">{{ detail.order.outTradeNo }}</a-descriptions-item>
          <a-descriptions-item label="返佣时间">{{ detail.order.createTime }}</a-descriptions-item>
        </a-descriptions>
      </div>
      <template #footer>
        <a-space />
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import Inputs from '@/views/finance/components/input.vue'
  import { onMounted, reactive, ref } from 'vue'
  import useCommonStore from '@/store/modules/common'
  import { usePagination, useRowKey, useTable, useTableHeight } from '@/hooks/table'
  import { formpost, get } from '@/api/http'
  import { rebateList, rebateListexport, rebaterecovery } from '@/api/url'
  import { Modal, Message } from '@arco-design/web-vue'
  const seachForm = ref({
    outTradeNo: '',
    userIds: '', //    客户ID
    channelIds: '', //  渠道ID
    seriesIds: '', //  系列ID
    setMealIds: '', //  套餐ID
    cards: '', //       充值卡号
    states: '', //     返佣状态 0等待返佣（订单状态为等待） 1成功 2回收 3回收失败
    addAmount: '', //   开始金额
    endAmount: '', //   结束金额
    addTime: '', //     开始时间
    endTime: '', //    结束金额
  })
  const tables = reactive({
    tableLoading: false,
    bordered: false,
    striped: false,
    expand: [1],
    isExpand: false,
  })
  const seachFormRef = ref()
  const common = useCommonStore()
  const userList: any = ref([])
  const channelList: any = ref([])
  const serieList: any = ref([])
  const mealList: any = ref([])
  const tableLoading = ref(false)
  const pagination = usePagination(doRefresh)
  const table = useTable()
  const loading = ref(false)
  const tableFooterRef = ref()
  const rowKey = useRowKey('id')
  const detail: any = ref({
    card: {},
    order: {},
    user: {},
  })
  const visible = ref(false)
  const tableColumns: any = reactive({
    list: [
      {
        title: '客户账号',
        key: 'userName',
        dataIndex: 'userName',
        ellipsis: true,
        tooltip: true,
        checked: true,
        width: 130,
      },
      {
        title: '卡号',
        key: 'card',
        dataIndex: 'card',
        checked: true,
        width: 270,
      },
      {
        title: '套餐名称',
        key: 'setMealName',
        dataIndex: 'setMealName',
        checked: true,
        width: 120,
      },

      {
        title: '返佣金额',
        key: 'amount',
        dataIndex: 'amount',
        checked: true,
        width: 120,
      },
      {
        title: '返佣状态',
        key: 'state',
        dataIndex: 'state',
        checked: true,
        width: 120,
      },
      {
        title: '返佣时间',
        key: 'addTime',
        dataIndex: 'addTime',
        checked: true,
        width: 190,
      },
      {
        title: '操作',
        key: 'action',
        dataIndex: 'action',
        checked: true,
        width: 70,
        fixed: 'right',
      },
    ],
  })
  //获取多卡
  function cardFn(value: any) {
    console.log(value)
    seachForm.value.cards = value
  }

  //收回返佣
  function rebateDel(item: any) {
    Modal.warning({
      title: '操作确认',
      content: '确定要收回此返佣吗？',
      cancelText: '取消',
      titleAlign: 'start',
      hideCancel: false,
      okText: '确定',
      onOk: () => {
        get({
          url: rebaterecovery,
          data: () => {
            return {
              orderId: item.orderId,
              userId: item.userId,
            }
          },
        }).then((res) => {
          if (res.code == 0) {
            Message.success(res.msg)
            doRefresh()
          }
        })
      },
    })
  }
  //获取详情
  function detailFn(val: any) {
    detail.value = JSON.parse(JSON.stringify(val))
    visible.value = true
  }
  //导出
  function exportList() {
    loading.value = true
    common.downLoadPosts(rebateListexport, seachForm.value, '返佣列表').then(() => {
      loading.value = false
    })
  }
  //重置
  function resetSeach() {
    seachFormRef.value?.resetFields()
    seachForm.value.addAmount = ''
    seachForm.value.endAmount = ''
    seachForm.value.cards = ''
    doRefresh(1)
  }
  //搜索
  function doRefresh(value?: number) {
    // eslint-disable-next-line prettier/prettier
    tableLoading.value = true
    if (value) {
      pagination.page = value
    }
    formpost({
      url: rebateList,
      data: () => {
        return {
          page: pagination.page,
          size: pagination.pageSize,
          ...seachForm.value,
          userIds: seachForm.value.userIds.toString(),
          channelIds: seachForm.value.channelIds.toString(),
          seriesIds: seachForm.value.seriesIds.toString(),
          setMealIds: seachForm.value.setMealIds.toString(),
          states: seachForm.value.states.toString(),
        }
      },
    })
      .then((res) => {
        tableLoading.value = false
        table.handleSuccess(res.data.list)
        pagination.setTotalSize((res.data as any).totalSize)
      })
      .catch(console.log)
  }
  //全部客户
  function getUser() {
    common.userLists().then((res: any) => {
      userList.value = res.data
    })
  }
  //全部渠道
  function getChannel() {
    common.channels().then((res: any) => {
      channelList.value = res.data
    })
  }
  //全部系列
  function getSeries() {
    common.seriess().then((res: any) => {
      serieList.value = res.data
    })
  }
  //全部套餐
  function getMeal() {
    common.mealListFn().then((res: any) => {
      mealList.value = res.data
    })
  }
  function onUpdateBorder(isBordered: boolean) {
    tables.bordered = isBordered
  }
  function onUpdateStriped(isStriped: boolean) {
    tables.striped = isStriped
  }
  onMounted(async () => {
    await getUser()
    await getChannel()
    await getSeries()
    await getMeal()
    await doRefresh()
  })
</script>
<style lang="less" scoped>
  :deep(.arco-modal) {
    .arco-modal-footer {
      text-align: right !important;
    }
  }
  :deep(.arco-modal-header .arco-modal-title) {
    display: flex;
    justify-content: flex-start !important;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
  }
  :deep(.arco-table-td-content button) {
    padding: 0px !important;
    margin-right: 8px;
    background: none !important;
  }
</style>
